package gui;

import classes.Servidor;
import controlador.LoginControlador;
import erro.ConexaoException;
import erro.ConsultaException;
import fachada.Fachada;
import java.awt.event.KeyEvent;
import java.awt.event.WindowEvent;
import java.util.Random;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import org.apache.commons.mail.EmailException;
import rn.CriptografarSenha;
import rn.Email;
import rn.TarefaStatus;

public class Login extends javax.swing.JFrame {

    public Login() {
        initComponents();
        try {
            TarefaStatus.alterarStatus();
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Ocorreu um erro ao tentar iniciar o programa.\n" + ex);
        }
        this.setLocationRelativeTo(null);
        //  this.getRootPane().setDefaultButton(btEntrar); 
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        gupoBotao = new javax.swing.ButtonGroup();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        textLogin = new javax.swing.JTextField();
        textSenha = new javax.swing.JPasswordField();
        ckEmail = new javax.swing.JCheckBox();
        jPanel2 = new javax.swing.JPanel();
        btEntrar = new javax.swing.JButton();
        btFechar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DO_NOTHING_ON_CLOSE);
        setTitle("Sistema Gerenciador de Atividades");
        addWindowListener(new java.awt.event.WindowAdapter() {
            public void windowClosed(java.awt.event.WindowEvent evt) {
                formWindowClosed(evt);
            }
            public void windowClosing(java.awt.event.WindowEvent evt) {
                formWindowClosing(evt);
            }
        });

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/brasao.png"))); // NOI18N

        jPanel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Login:");

        jLabel3.setText("Senha:");

        textLogin.setNextFocusableComponent(textSenha);

        textSenha.setNextFocusableComponent(btEntrar);

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(textSenha, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(textLogin, javax.swing.GroupLayout.PREFERRED_SIZE, 155, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(20, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(textLogin, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(textSenha, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(35, Short.MAX_VALUE))
        );

        ckEmail.setFont(new java.awt.Font("Tahoma", 0, 10)); // NOI18N
        ckEmail.setText("Esqueceu a senha?");
        ckEmail.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                ckEmailActionPerformed(evt);
            }
        });

        btEntrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/salvar.png"))); // NOI18N
        btEntrar.setText("Entrar");
        btEntrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btEntrarActionPerformed(evt);
            }
        });
        btEntrar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btEntrarKeyPressed(evt);
            }
        });

        btFechar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Imagens/cancelar.png"))); // NOI18N
        btFechar.setText("Fechar");
        btFechar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btFecharActionPerformed(evt);
            }
        });
        btFechar.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                btFecharKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btEntrar, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                    .addComponent(btFechar, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(btEntrar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btFechar)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(ckEmail)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addComponent(jLabel1))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 18, Short.MAX_VALUE)
                .addComponent(ckEmail)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btEntrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btEntrarActionPerformed
        TarefaListarTela tl = new TarefaListarTela();
        EventoMostrar em = new EventoMostrar();
        ServidorExibir se = new ServidorExibir();
        TarefaMostrar tm = new TarefaMostrar();
        LoginControlador lv = new LoginControlador();
        LoginControlador.login = textLogin.getText().toLowerCase().trim();
        LoginControlador.senhaAtual = CriptografarSenha.encripta(textSenha.getText().trim());//
        try {
            lv.validar();
            if (lv.getSituacao().equals("logado")) {
                tl.lbLogado.setText(LoginControlador.nome);
                switch (LoginControlador.nivel) {
                    case 1:
                        tl.setExtendedState(JFrame.MAXIMIZED_BOTH);
                        tl.setLocationRelativeTo(null);
                        tl.setVisible(true);
                        this.setVisible(false);
                        break;
                    case 2:
                        tl.setExtendedState(JFrame.MAXIMIZED_BOTH);
                        tl.setLocationRelativeTo(null);
                        tl.setVisible(true);
                        this.setVisible(false);
                        break;
                    case 3:
                        tl.rdIncluídaPeloLogado.setVisible(false);
                        tl.menuCadastrar.setVisible(true);
                        tl.menuAgenda.setVisible(true);
                        tl.menuCadastrarLotacao.setVisible(false);
                        tl.menuCadastrarServidor.setVisible(false);
                        tl.menuCargos.setVisible(false);
                        tl.menuCadastrarTarefa.setVisible(false);
                        tl.menuCadastrarEvento.setVisible(false);
                        em.btExcluir.setEnabled(false);
                        se.btAlterar.setEnabled(false);
                        tm.btExcluir.setVisible(false);
                        tm.btReiniciar.setVisible(false);
                        tm.btTarefaConc.setVisible(false);
                        tm.btTarefaInic.setVisible(false);
                        tl.setExtendedState(JFrame.MAXIMIZED_BOTH);
                        tl.setVisible(true);
                        this.setVisible(false);
                        break;
                    case 4:
                        JOptionPane.showMessageDialog(null, "Você não tem acesso ao sistema. Por favor contate o administrador.");
                        textLogin.setText("");
                        textSenha.setText("");
                        textLogin.grabFocus();
                        break;
                }
            } else {
                JOptionPane.showMessageDialog(null, "Login ou Senha incorretos.");
                textLogin.setText("");
                textSenha.setText("");
                repaint();
            }
        } catch (ConexaoException ex) {
            JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
        } catch (ConsultaException ex) {
            JOptionPane.showMessageDialog(null, "Login ou Senha não cadastrados.\n" + ex);
        } catch (Exception e) {
            JOptionPane.showMessageDialog(null, e);
        }
    }//GEN-LAST:event_btEntrarActionPerformed

    private void ckEmailActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_ckEmailActionPerformed
        Servidor s = new Servidor();
        Fachada f = new Fachada();
        LoginControlador lv = new LoginControlador();
        Email email = new Email();
        String novaSenha = new String();
        if (textLogin.getText().equals("")) {
            JOptionPane.showMessageDialog(null, "Por favor digite o seu login.");
            textLogin.setText("");
            textLogin.grabFocus();
        } else {
            s.setLogin(textLogin.getText().trim().toLowerCase());
            try {
                s = f.pesquisarLogin(s);
                if (s.getSenha() == null) {
                    JOptionPane.showMessageDialog(null, "Usuário não cadastrado. Por favor contate o administrador do sistema.");
                    textLogin.setText("");
                    ckEmail.setSelected(false);
                    textLogin.grabFocus();
                } else {
                    try {
                        String str = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                        StringBuffer sb = new StringBuffer();
                        Random random = new Random();
                        for (int i = 0; i < 36; ++i) {
                            sb.append(str.charAt(random.nextInt(36)));
                        }
                        for (int j = 0; j < 6; j++) {
                            novaSenha = novaSenha + String.valueOf(sb.charAt(j));
                        }
                    } catch (Exception e) {
                        JOptionPane.showMessageDialog(null, "Erro ao tentar gerar uma nova senha!");
                    }                    
                    LoginControlador.login = s.getLogin();
                    s.setLogin(LoginControlador.login);
                    f.pesquisarLogin(s);
                    s.setSenha(CriptografarSenha.encripta(novaSenha));
                    f.criarSenha(s);

                    Email.conteudo = "Senha gerada pelo sistema. Por favor altere a sua senha no próximo acesso.\n "
                            + "Senha: " + novaSenha;
                    Email.assunto = "Senha de acesso ao sistema SGA";
                    Email.nome = s.getNome();
                    Email.destino = s.getEmailProf();
                    try {
                        email.enviaEmail();
                        JOptionPane.showMessageDialog(null, "Foi enviado um e-mail para " + s.getEmailProf() + " com sua senha.");
                        ckEmail.setSelected(false);
                    } catch (EmailException ex) {
                        JOptionPane.showMessageDialog(null, "Não foi possível enviar o e-mail." + ex);
                    }
                }
            } catch (ConexaoException ex) {
                JOptionPane.showMessageDialog(null, "Não foi possível conectar-se ao banco de dados!\n" + ex);
            } catch (ConsultaException ex) {
                JOptionPane.showMessageDialog(null, "Usuário não cadastrado. Por favor contate o administrador do sistema.\n" + ex);
            }
        }
    }//GEN-LAST:event_ckEmailActionPerformed

    private void btEntrarKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btEntrarKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btEntrarActionPerformed(null);
        }
    }//GEN-LAST:event_btEntrarKeyPressed

    private void btFecharKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_btFecharKeyPressed
        if (KeyEvent.getKeyText(evt.getKeyCode()).equals("Enter")) {
            btFecharActionPerformed(null);
        }
    }//GEN-LAST:event_btFecharKeyPressed

    private void btFecharActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btFecharActionPerformed
        int selectedOption = JOptionPane.showConfirmDialog(null, "Deseja realmente sair do sistema?", "Sistema informa:", JOptionPane.YES_NO_OPTION);
        if (selectedOption == JOptionPane.YES_OPTION) {
            System.exit(0);
        } else {
            this.repaint();
        }
    }//GEN-LAST:event_btFecharActionPerformed

    private void formWindowClosing(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosing
        if (evt.getID() == WindowEvent.WINDOW_CLOSING) {
            int selectedOption = JOptionPane.showConfirmDialog(null, "Deseja realmente sair do sistema?", "Sistema informa:", JOptionPane.YES_NO_OPTION);
            if (selectedOption == JOptionPane.YES_OPTION) {
                System.exit(0);
            } else {
                this.repaint();
            }
        }
    }//GEN-LAST:event_formWindowClosing

    private void formWindowClosed(java.awt.event.WindowEvent evt) {//GEN-FIRST:event_formWindowClosed
    }//GEN-LAST:event_formWindowClosed

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Login.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new Login().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btEntrar;
    private javax.swing.JButton btFechar;
    private javax.swing.JCheckBox ckEmail;
    private javax.swing.ButtonGroup gupoBotao;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JTextField textLogin;
    private javax.swing.JPasswordField textSenha;
    // End of variables declaration//GEN-END:variables
}
